package cn.tedu.bookstore.controller;

import cn.tedu.bookstore.mapper.UserMapper;
import cn.tedu.bookstore.pojo.dto.UserDTO;
import cn.tedu.bookstore.pojo.dto.UserLoginDTO;
import cn.tedu.bookstore.pojo.vo.UserRegVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/user/reg")
    public int reg(@RequestBody UserDTO user){
        UserRegVO u = mapper.selectByPhone(user.getPhone());
        String phone = user.getPhone();
        String u1 = user.getUsername();
        String regex = "[1][34578][0-9]{9}";
        if(phone.matches(regex)){
            if(u!=null){
                return 3;   //电话号已存在
            }else {
                String u2 = mapper.selectByUsername(u1);
                if(u2!= null){
                    return 4;   //用户名已存在
                }
            }
            mapper.insert(user);
            return 1;   //注册成功
        }else {
            System.out.println("格式不正确");
            return 2;   //格式不正确
        }
    }
    @RequestMapping("/user/login")
    public int login(@RequestBody UserLoginDTO user,HttpServletResponse response, HttpSession session ){
        UserRegVO u = mapper.selectByPhone(user.getPhone());
        if(u!=null){
            if(user.getPassword().equals(u.getPassword())){
                //如果选择了保存记住我就走这块的代码
                if(user.getRem()){
                    Cookie c1 = new Cookie("phone", user.getPhone());
                    c1.setMaxAge(60*60*24*7);
                    Cookie c2 = new Cookie("password", user.getPassword());
                    c1.setPath("/");
                    c2.setPath("/");
                    c2.setMaxAge(60*60*24*7);
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                //把当前登录的用户对象保存到Session里面
                session.setAttribute("user",u);
                return 1; //登录成功
            }
            return 2; //密码错误
        }
        return 3; //用户不存在
    }
}
